package com.yanghui.lingyue.utils.netUtils

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.icedata.sika.util.Logger
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.util.*
import java.util.concurrent.TimeUnit

object HttpJsonUtils {

    var POST = 0
    var GET = 1

    /**
     * 从url中直接获取字符串
     *
     * @param url url地址
     * @return 字符串
     */
    fun getStringFromURLMethodGet(url: String): String? {
        val client: OkHttpClient = OkHttpClient.Builder()
            .callTimeout(5000, TimeUnit.MILLISECONDS)
            .build()
        val request: Request = Request.Builder()
            .url(url)
            .get()
            .build()
        var response: Response? = null
        val JsonBack: String
        var result: String? = null
        try {
            response = client.newCall(request).execute()
            JsonBack = Objects.requireNonNull(response.body)!!.string()
            result = JsonBack
        } catch (e: Exception) {
            Logger.logError(e)
        }
        if (response != null) {
            Objects.requireNonNull(response.body)!!.close()
        }
        return result
    }

    /**
     * 从url中获取json文件
     *
     * @param url url地址
     * @return json对象
     */
    fun getJsonObjectFromURLMethodGet(url: String): JSONObject {
        return JSON.parseObject(getStringFromURLMethodGet(url))
    }

    /**
     * 添加url参数
     *
     * @param originUrl        初始url
     * @param paramKey   参数名
     * @param paramValue 参数值
     * @return 修正后的url
     */
    fun addStringParamMethodGet(originUrl: String, paramKey: String, paramValue: String?): String {
        var url = originUrl
        if (!url.endsWith("?")) {
            url += "?"
        }
        return "$url$paramKey=$paramValue"
    }

    /**
     * 批量添加url参数
     *
     * @param originUrl    初始url
     * @param params 参数列表
     * @return 修正后的url
     */
    fun addAllStringParamMethodGet(originUrl: String, params: Map<String, String?>): String {
        var url = originUrl
        for (paramKey in params.keys) {
            url = addStringParamMethodGet(url, paramKey, params[paramKey])
        }
        return url
    }

}